// 云函数入口文件
const cloud = require('wx-server-sdk')

cloud.init()


// 云函数入口函数
exports.main = async (event, context) => {
  const wxContext = cloud.getWXContext()

  console.log("[debug info] hello world,is time to clean database.")

  var timestamp = Date.parse(new Date());
  console.log("[当前时间]: ",timestamp)
  timestamp -= (60 * 60 * 24 * 1000 * 1)
  console.log("[查询条件][小于该时间][ms]: ",timestamp)

  //按条件查找数据库
  try {
    const db = cloud.database()
    const _ = db.command
    var all_op_number = 0
    
    res = await db.collection('event').where({
      event:"photo",
      event_time: _.lt(timestamp)
    }).get()
    
    console.log("[按条件查询数据库][数量]: ",res.data.length)

    if(res.data.length == 0)
    {
      console.log("[没有需要清理]")
      console.log("[操作完毕本次共删除数量为]: ",all_op_number)
      return {
        event,
        openid: wxContext.OPENID,
        appid: wxContext.APPID,
        unionid: wxContext.UNIONID,
      }
    }

    console.log("[按条件查询数据库][成功]: ",res)
    
    var op_number = res.data.length
    
    /** api一次限制最多删除50个文件 */
    if(op_number > 50)
    op_number = 50

    all_op_number += op_number

    console.log("[本次实际操作删除数量]: ",op_number)
    /**
     * 生成删除文件表准备删除
     */
    var dele_list_file = []
    for(var i = 0;i < op_number;i ++)
    dele_list_file[i] = "cloud://lononcam-7gzsafx250a9853b.6c6f-lononcam-7gzsafx250a9853b-1304353880/" + 'image/' + res.data[i].event_data

    console.log("[dele_list]",dele_list_file)
    
    /**
     * 执行删除文件
     */
    res2 = await cloud.deleteFile({
      fileList: dele_list_file,
    })

    console.log("[删除文件结果]: ",res2)

    /**
     * 生成删除数据库表准备删除
     */
    var dele_list_database = []
    for(var i = 0;i < op_number;i ++)
    dele_list_database[i] = res.data[i].event_data

    /**
     * 执行数据库
     */
    for(var k = 0;k < op_number;k ++)
    {
      res3 = await db.collection('event').where({
        event_data: dele_list_database[k]
      }).remove()
      console.log("[删除记录结果]: ",res3)
    }
  }
  catch(e)
  {
    console.log(e)
  }
  
  console.log("[操作完毕本次共删除数量为]: ",all_op_number)

  return {
    event,
    openid: wxContext.OPENID,
    appid: wxContext.APPID,
    unionid: wxContext.UNIONID,
  }
}



